#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GPS位置获取调试脚本
用于诊断获取当前位置失败的问题
"""

import sys
import os
import asyncio
from datetime import datetime

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.services.gps_service import GPSApiService
from app.crud.api_config import api_config
from app.crud.shipment import shipment
from app.db.session import SessionLocal

def debug_gps_location(shipment_id: int = 1):
    """调试GPS位置获取"""
    print("=" * 60)
    print(f"调试货物ID {shipment_id} 的GPS位置获取")
    print("=" * 60)
    
    db = SessionLocal()
    try:
        # 1. 检查货物是否存在
        print("1️⃣ 检查货物信息...")
        shipment_obj = shipment.get(db, id=shipment_id)
        if not shipment_obj:
            print(f"❌ 错误: 货物ID {shipment_id} 不存在")
            return False
            
        print(f"✅ 找到货物: {shipment_obj.number_no}")
        print(f"   设备号: {shipment_obj.mac_id}")
        print(f"   取货仓库: {shipment_obj.pickup_warehouse}")
        print(f"   卸货仓库: {shipment_obj.delivery_warehouse}")
        
        # 2. 检查GPS API配置
        print("\n2️⃣ 检查GPS API配置...")
        gps_config = api_config.get_by_code(db, code="gpsApi")
        if not gps_config:
            print("❌ 错误: 未找到GPS API配置")
            print("请在系统管理 → 外部API配置中添加代码为 'gpsApi' 的配置")
            return False
            
        print(f"✅ 找到GPS API配置")
        print(f"   API地址: {gps_config.api_url}")
        print(f"   API用户: {gps_config.api_user}")
        print(f"   API密码: {'*' * len(gps_config.api_pwd) if gps_config.api_pwd else 'None'}")
        
        # 3. 创建GPS服务并测试登录
        print("\n3️⃣ 测试GPS系统登录...")
        gps_service = GPSApiService(
            api_url=gps_config.api_url,
            api_user=gps_config.api_user,
            api_pwd=gps_config.api_pwd
        )
        
        login_result = gps_service.login()
        if not login_result['success']:
            print(f"❌ GPS登录失败: {login_result['message']}")
            print("   请检查API配置中的地址、用户名和密码是否正确")
            return False
            
        print("✅ GPS系统登录成功")
        print(f"   会话令牌: {login_result['data'].get('mds', 'Unknown')[:20]}...")
        
        # 4. 查找设备
        print(f"\n4️⃣ 查找设备 {shipment_obj.mac_id}...")
        device_result = gps_service.find_device_by_mac_id(shipment_obj.mac_id)
        
        if not device_result['success']:
            print(f"❌ 设备查找失败: {device_result['message']}")
            
            # 获取所有设备列表进行对比
            print("\n📋 获取设备列表进行诊断...")
            device_list_result = gps_service.get_device_list()
            if device_list_result['success']:
                devices = device_list_result['data']
                print(f"   找到 {len(devices)} 个设备:")
                
                # 显示前10个设备
                for i, device in enumerate(devices[:10]):
                    mac_id = device.get('macid', 'N/A')
                    name = device.get('fullName', 'N/A')
                    online = '在线' if device.get('offline') == '1' else '离线'
                    print(f"   {i+1:2d}. {mac_id:15} | {name:20} | {online}")
                
                if len(devices) > 10:
                    print(f"   ... 还有 {len(devices) - 10} 个设备")
                    
                # 检查是否有相似的设备号
                similar_devices = []
                target_mac = shipment_obj.mac_id.lower()
                for device in devices:
                    device_mac = device.get('macid', '').lower()
                    if target_mac in device_mac or device_mac in target_mac:
                        similar_devices.append(device)
                
                if similar_devices:
                    print(f"\n🔍 找到 {len(similar_devices)} 个相似的设备号:")
                    for device in similar_devices:
                        print(f"   - {device.get('macid')} ({device.get('fullName', 'N/A')})")
            
            return False
            
        print("✅ 设备查找成功")
        device_info = device_result['data']
        print(f"   设备名称: {device_info.get('fullName', 'N/A')}")
        print(f"   车牌号: {device_info.get('platenumber', 'N/A')}")
        print(f"   在线状态: {'在线' if device_info.get('offline') == '1' else '离线'}")
        print(f"   设备类型: {device_info.get('macName', 'N/A')}")
        print(f"   到期时间: {device_info.get('blockdate', 'N/A')}")
        print(f"   ObjectID: {device_info.get('objectid', 'N/A')}")
        
        # 5. 获取当前位置
        print(f"\n5️⃣ 获取设备当前位置...")
        location_result = gps_service.get_device_current_location(shipment_obj.mac_id)
        
        if not location_result['success']:
            print(f"❌ 获取位置失败: {location_result['message']}")
            
            # 如果设备离线，给出建议
            if device_info.get('offline') != '1':
                print("💡 建议:")
                print("   - 检查设备是否开机且有信号")
                print("   - 确认设备是否在有GPS信号的地方")
                print("   - 联系设备供应商检查设备状态")
            
            return False
            
        print("✅ 成功获取设备位置")
        location_data = location_result['data']
        print(f"   设备名称: {location_data.get('device_name', 'N/A')}")
        print(f"   设备编号: {location_data.get('device_id', 'N/A')}")
        print(f"   经度: {location_data.get('lng', 0)}")
        print(f"   纬度: {location_data.get('lat', 0)}")
        print(f"   速度: {location_data.get('speed', 0)} km/h")
        print(f"   定位类型: {location_data.get('location_type', 'Unknown')}")
        print(f"   精度: {location_data.get('precision', 'Unknown')}")
        print(f"   定位时间: {location_data.get('device_time', 'Unknown')}")
        
        print("\n" + "=" * 60)
        print("🎉 GPS位置获取调试完成！一切正常")
        return True
        
    except Exception as e:
        print(f"\n❌ 调试过程中发生异常: {str(e)}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        db.close()

if __name__ == "__main__":
    print("🚀 开始GPS位置获取调试...")
    print(f"Python版本: {sys.version}")
    print(f"当前工作目录: {os.getcwd()}")
    print()
    
    # 可以修改这里的shipment_id来调试不同的货物
    shipment_id = 1
    
    success = debug_gps_location(shipment_id)
    
    if not success:
        print("\n❌ 调试发现问题，请根据上述信息进行修复")
        sys.exit(1)
    else:
        print("\n✅ 调试完成，GPS功能正常")